//
//  CellPictureView.m
//  Budejie
//
//  Created by 远成物流 on 2017/5/16.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "CellPictureView.h"
#import "ShowBigPictureController.h"
#import "UIImageView+Download.h"

@interface CellPictureView ()
@property (weak, nonatomic) IBOutlet UIImageView *placeholderView;
@property (weak, nonatomic) IBOutlet UIImageView *picture;
@property (weak, nonatomic) IBOutlet UIImageView *gifIcon;
@property (weak, nonatomic) IBOutlet UIButton *showbig;

@end

@implementation CellPictureView

-(void)awakeFromNib{
    [super awakeFromNib];
    
    self.autoresizingMask = UIViewAutoresizingNone;
    
    self.picture.userInteractionEnabled = YES;
    [self.picture addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBigPicture)]];
}

//查看大图
-(void)showBigPicture{
    ShowBigPictureController *showBig = [[ShowBigPictureController alloc] init];
    showBig.topic = self.topic;
    [self.window.rootViewController presentViewController:showBig animated:YES completion:nil];
}

- (IBAction)showBigAction:(id)sender {
    
    [self showBigPicture];
}

-(void)setTopic:(EssenceTopic *)topic{
    _topic = topic;
    //图片
    self.placeholderView.hidden = NO;
    [self.picture setOriginalImage:topic.image1 thumbnailImage:topic.image0 placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        if (!image) {
            return ;
        }
        
        self.placeholderView.hidden = YES;
        
        //处理超长图片
        if (topic.isBigPicture) {
            CGFloat imageW = topic.middleFrame.size.width;
            CGFloat imageH = imageW * topic.height / topic.width;
            
            // 开启上下文
            UIGraphicsBeginImageContext(CGSizeMake(imageW, imageH));
            // 绘制图片
            [self.picture.image drawInRect:CGRectMake(0, 0, imageW, imageH)];
            self.picture.image = UIGraphicsGetImageFromCurrentImageContext();
            //关闭上下文
            UIGraphicsEndImageContext();
        }
        
    }];
    
    //gif
    self.gifIcon.hidden = !topic.is_gif;
    
    //查看大图按钮
    if (topic.isBigPicture) {
        self.showbig.hidden = NO;
        self.picture.contentMode = UIViewContentModeTop;
        self.picture.clipsToBounds = YES;
    }else{
        self.showbig.hidden = YES;
        self.picture.contentMode = UIViewContentModeScaleToFill;
        self.picture.clipsToBounds = NO;
    }
}

@end
